package assetservicelogic

import (
	"context"
	"property_service/dao/model"
	"property_service/dao/query"
	"property_service/internal/svc"
	"property_service/property_service"
	"property_service/utils/BeanUtils"
	"property_service/utils/result"

	"github.com/zeromicro/go-zero/core/logx"
)

type AssetPurchaseRequestAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAssetPurchaseRequestAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AssetPurchaseRequestAddLogic {
	return &AssetPurchaseRequestAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// AssetPurchaseRequestAdd 创建采购申请单表
func (l *AssetPurchaseRequestAddLogic) AssetPurchaseRequestAdd(in *property_service.AssetPurchaseRequest) (*property_service.ResponseId, error) {
	// 获取采购申请单表模型的查询构造器
	m := query.Use(l.svcCtx.Gorm).AssetPurchaseRequest
	// 创建一个新的采购申请单表模型对象，不包含ID、UpdatedAt、CreatedAt字段
	mod := &model.AssetPurchaseRequest{
		RequestCode:    in.RequestCode,                            // 申请单号
		PurchaseMonth:  BeanUtils.GetDateFormat(in.PurchaseMonth), // 购置年月
		RequestType:    in.RequestType,                            // 申请类型
		RequestTypeID:  in.RequestTypeID,                          //申请类型id
		PlanNumber:     in.PlanNumber,                             // 计划号
		RequestDept:    in.RequestDept,                            // 申请科室
		RequestDeptID:  in.RequestDeptID,                          // 申请科室id
		Applicant:      in.Applicant,                              // 申请人
		ApplicantID:    in.ApplicantID,                            // 申请人id
		CompileDate:    BeanUtils.GetDateFormat(in.CompileDate),   // 编制日期
		Remarks:        in.Remarks,                                // 备注
		PurchaseStatus: in.PurchaseStatus,                         // 采购状态（0-申请 1-成功）
		StatusID:       in.StatusID,                               // 状态ID(关联状态表StatusDisposition)
		StatusName:     in.StatusName,                             // 采购状态（0-申请 1-成功）
		StockID:        in.StockID,                                // 仓库ID
		TenantID:       in.TenantID,                               // 租户ID
		CreatedAtuser:  in.CreatedAtuser,                          // 创建用户
	}

	// 使用上下文执行创建操作
	if err := m.WithContext(l.ctx).Create(mod); err != nil {
		res, err := result.Err(err).Ed()
		return l.buildResponse(mod.ID, res, err)
	}
	// 创建成功，返回成功响应
	res, err := result.Suc().AddEd()
	return l.buildResponse(mod.ID, res, err)
}

// 在 AssetPurchaseRequestAddLogic 结构体中添加辅助方法
func (l *AssetPurchaseRequestAddLogic) buildResponse(id int64, res *property_service.Response, err error) (*property_service.ResponseId, error) {
	return &property_service.ResponseId{
		Id:      id,
		Code:    res.Code,
		Message: res.Message,
	}, err
}
